<template>
  <view class="login-page">
    <!-- 微信环境登录状态显示 -->
    <view class="loading" v-if="!showPhoneLogin">
      <text>{{ loginStatusText }}</text>
    </view>
    
    <!-- 非微信浏览器显示登录表单 -->
    <view class="phone-login" v-if="showPhoneLogin">
      <view class="title">账号登录</view>
      <view class="input-group">
        <input 
          type="text"  
          placeholder="请输入手机号" 
          v-model="inputContent"
          class="phone-input"
          @input="clearError"
        />
      </view>
	  <view>测试环境/正式环境：手机号</view>
      <button 
        class="login-btn" 
        @click="loginWithInput"
        :disabled="isLoading"  
      >
        <text v-if="!isLoading">登录</text>
        <text v-if="isLoading">登录中...</text>
      </button>
      <view class="error-message" v-if="errorMessage">{{ errorMessage }}</view>
    </view>
  </view>
</template>

<script>
import store from '../../common/store.js'
import { navigateToPage } from '../../common/loginInterceptor.js'
import utils from '../../common/utils';

export default {
  data() {
    return {
      code: '',
      loginStatusText: "正在登录中...",
      showPhoneLogin: false,
      inputContent: '',  // 改为通用输入内容变量
      errorMessage: '',
      isLoading: false,
      sftc: ''
    }
  },
  
  onLoad(options) {
    this.sftc = options.sftc || '';
    //store.clearLoginInfo();
    const isLogin = store.isLogin();
    console.info("登录状态：" + isLogin);
    
    if (isLogin) {
      this.loginStatusText = "已登录，正在跳转到首页..."
      setTimeout(() => {
        navigateToPage('/pages/index/index').catch(err => {
          console.error('登录页跳首页失败：', err)
          this.loginStatusText = "跳转失败，请刷新页面"
        })
      }, 500)
    } else {
      const isWechat = this.isWechatBrowser();
      console.info("是否微信浏览器：" + isWechat);
      
      if (isWechat) {
        if (options.code) {
          this.code = options.code;
          this.onLogin(this.code)
        }
        
        if (!this.code) {
          let redirect = "http://stjk.whsyzj.com/cwqf/pages/login/login";
          let send_data = {"redirect": redirect, "state": '123'};
          console.info("redirect：" + redirect);
          console.info("send_data" + send_data);
          this.loginStatusText = "准备获取用户信息...";
          this.$myRequest.get(getApp().globalData.qyhAuth + "/buildOauth2Url", send_data).then(res => {
            console.info("返回：" + JSON.stringify(res));
            if (res.code == 200) {
              this.loginStatusText = "即将跳转授权";
              window.location.href = res.data;
            } else {
              this.loginStatusText = "没有获取到code！登录失败！";
            }
          });
        }
      } else {
        this.showPhoneLogin = true;
        this.loginStatusText = "1";
      }
    }
  },
  
  methods: {
    isWechatBrowser() {
      const userAgent = window.navigator.userAgent.toLowerCase();
      return userAgent.indexOf('micromessenger') !== -1;
    },
    
    clearError() {
      this.errorMessage = '';
    },
    
    onLogin(code) {
      this.loginStatusText = "正在登录中...";
      this.$utils.showLoading("登录中...");
      
      let data = {
        code: code,
        timestamp: this.$utils.getTimestamp(),
      };
      
      this.$myRequest.post(getApp().globalData.loginQyh, data).then(res => {
        uni.hideLoading();
        console.info(JSON.stringify(res));
        if (res.code === 200) {
          let a = JSON.parse(utils.decrypt(res.data, "NLfZ3aIOg77E2rT8", "0102030405060708"));
          let user = {
            userid: a.c,
            token: a.token,
            aesKey: a.a,
            aesIv: a.b
          };
          console.info("登录信息：" + JSON.stringify(user));
          
          store.setLoginInfo(user);
          console.info("同步成功！：" + JSON.stringify(user));
          this.loginStatusText = "登录成功，正在跳转到首页..."
          
          this.handleRedirect();
        } else {
          this.loginStatusText = `登录失败：${res.msg || '未知错误'}`;
          this.$utils.toast(res.msg);
        }
      }).catch(err => {
        uni.hideLoading();
        this.loginStatusText = `登录异常：${err.message || '网络错误'}`;
        this.$utils.toast(err.message || '登录失败，请重试');
      });
    },
    
    // 改为通用输入登录方法
    loginWithInput() {
      // 移除手机号校验逻辑
      this.isLoading = true;
      this.errorMessage = "";
      
      // 使用输入的内容作为登录参数
      const data = {
        code: this.inputContent,  // 传递输入的内容
        timestamp: this.$utils.getTimestamp()
      };
      
      this.$myRequest.post(getApp().globalData.loginSjh, data).then(res => {
        this.isLoading = false;
        
        if (res.code === 200) {
          let a = JSON.parse(utils.decrypt(res.data, "NLfZ3aIOg77E2rT8", "0102030405060708"));
          let user = {
            userid: a.c,
            token: a.token,
            aesKey: a.a,
            aesIv: a.b
          };
          
          store.setLoginInfo(user);
          
          this.showPhoneLogin = false;
          this.loginStatusText = "登录成功，正在跳转到首页...";
          
          setTimeout(() => {
            this.handleRedirect();
          }, 1000);
        } else {
          this.errorMessage = res.msg || "登录失败，请重试";
        }
      }).catch(err => {
        this.isLoading = false;
        this.errorMessage = err.message || "网络异常，请重试";
      });
    },
    
    handleRedirect() {
      if (this.sftc === "1") {
        this.onClose();
      } else {
        uni.navigateTo({
          url: "/pages/index/index",
          fail: (err) => {
            console.error("跳转首页失败：", err);
            this.loginStatusText = "跳转失败，请刷新页面";
          }
        });
      }
    },
    
    onClose() {
      uni.navigateBack({
        delta: 1
      });
    }
  }
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  padding: 0 40rpx;
}

.loading {
  font-size: 32rpx;
  color: #666;
  text-align: center;
  padding: 20rpx;
}

.phone-login {
  width: 100%;
  max-width: 500rpx;
  background-color: #fff;
  padding: 60rpx 40rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-bottom: 60rpx;
}

.input-group {
  margin-bottom: 40rpx;
}

.phone-input {
  width: 90%;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 20rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  font-size: 32rpx;
}

.phone-input:focus {
  border-color: #07c160;
  outline: none;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #07c160;
  color: #fff;
  font-size: 34rpx;
  border-radius: 8rpx;
  border: none;
  margin-bottom: 20rpx;
}

.login-btn:disabled {
  background-color: #999;
  opacity: 0.7;
}

.error-message {
  color: #f53f3f;
  font-size: 28rpx;
  text-align: center;
  min-height: 32rpx;
}
</style>
